package com.tool.builder.BuildClass;

import com.tool.bean.Constants;
import com.tool.bean.TableInfo;
import com.tool.builder.BuildHelper.BuildComment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * 创建持久层
 */
public class BuildMapper {
    private static final Logger logger = LoggerFactory.getLogger(BuildQuery.class);

    public static void execute(TableInfo tableInfo) {
        File folder = new File(Constants.PATH_MAPPER);
        if(!folder.exists()) {   // 路径不存在则创建
            folder.mkdirs();
        }

        String className = tableInfo.getBeanName() + "Mapper";

        File mapperFile = new File(folder, className + ".java");

        OutputStream out = null;
        OutputStreamWriter outw = null;
        BufferedWriter bw = null;
        try {
            out = new FileOutputStream(mapperFile);
            outw = new OutputStreamWriter(out, "utf8");
            bw = new BufferedWriter(outw);

            bw.write("package " + Constants.PACKAGE_MAPPER + ";");
            bw.newLine();
            bw.newLine();

            bw.write("import com.baomidou.mybatisplus.core.mapper.BaseMapper;");
            bw.newLine();
            bw.write("import " + Constants.PACKAGE_PO + "." + tableInfo.getBeanName() + ";");
            bw.newLine();
            bw.write("import org.apache.ibatis.annotations.Mapper;");
            bw.newLine();
            bw.newLine();

            // 构建类注释
            BuildComment.createClassComment(bw, tableInfo.getComment() + "持久层");
            bw.newLine();
            bw.newLine();

            bw.write("@Mapper");
            bw.newLine();

            bw.write("public interface " + className + " extends BaseMapper<" + tableInfo.getBeanName() + "> {");
            bw.newLine();
            bw.newLine();

            bw.write("}");
            bw.flush();
        }   catch (Exception e) {
            logger.error("创建Mapper失败", e);
        }  finally {
            if(outw !=null) {
                try {
                    outw.close();
                }   catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

}
